import axios, { AxiosError, type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 配置新建一个 axios 实例
const request = axios.create({
  baseURL: '/api',
  timeout: 500000
})

// 添加请求拦截器
request.interceptors.request.use((config) => {
  const token = sessionStorage.getItem('Authorization')
  if (token) {
    ;(config.headers as AxiosRequestHeaders).Authorization = token
  } else {
    ;(config.headers as AxiosRequestHeaders).Authorization = `309_token`
  }
  return config
})

// 添加响应拦截器
request.interceptors.response.use(
  /* 约束一下response */
  (response: AxiosResponse<ResponseData<any>>) => {
    let res = response.data
    if (res.code === 3) {
      ElMessage.warning('登录超时请重新登录')
      sessionStorage.removeItem('Authorization')
      setTimeout(() => {
        window.location.href = '/login'
      }, 1000)
    }
    if (res.code === 200) {
      return res.data
    } else {
      return res
    }
  }
)

export default request
